#!/bin/bash -e
source reporting.sh

REPORT=/tmp/report.txt
TEST_NAME="cloud.udmi.pointset"
TEST_DESCRIPTION="Validates device payload against the UDMI schema"
TEST_SUMMARY=""
LOG=/tmp/udmi.log

# Necessary to reach gcp. Should be done by framework but this works for now.
route add default gw $GATEWAY_IP

route -n
ping -c 2 172.217.164.106 || true
arp -n
ip addr

gcp_cred=/config/inst/gcp_service_account.json
gcp_topic=target
schema_path=schemas/udmi

device_id=`jq -r .device_id /config/device/module_config.json`

# Do basic network connectivity check
cat /etc/resolv.conf
ping -c 2 172.217.164.106
ping -c 2 pubsub.googleapis.com

if [ "$device_id" == null ]; then
    echo Device id is null, skipping.
    RESULT_AND_SUMMARY="RESULT skip $TEST_NAME No device id"
    write_out_result $REPORT \
                     "$TEST_NAME" \
                     "$TEST_DESCRIPTION" \
                     "Device id is null, skipping." \
                     "$RESULT_AND_SUMMARY"
    exit 0
fi

if [ ! -f $gcp_cred ]; then
    RESULT_AND_SUMMARY="RESULT skip $TEST_NAME No credentials"
    write_out_result $REPORT \
                     "$TEST_NAME" \
                     "$TEST_DESCRIPTION" \
                     "Missing $gcp_cred file, skipping udmi validation." \
                     "$RESULT_AND_SUMMARY"
    exit 0
fi

project_id=`jq -r .project_id $gcp_cred`
service_id=`jq -r .client_email $gcp_cred`
service_id=${service_id%@*}

export GOOGLE_APPLICATION_CREDENTIALS=$gcp_cred
export GOOGLE_CLOUD_PROJECT=$project_id

echo Using credentials from $GOOGLE_APPLICATION_CREDENTIALS
echo Extracted project $project_id
echo Extracted service $service_id
echo Configured topic is $gcp_topic
echo Configured schema is $schema_path
echo Target device is $device_id
echo

timeout 60 validator/bin/validate $PWD/$schema_path pubsub:$gcp_topic $service_id-$HOSTNAME || true

base=validations/devices/$device_id/pointset

ls -l $base* || true

if [ -f "$base.out" ]; then
    result=fail
    detail=`head -n 1 $base.out`
elif [ -f "$base.json" ]; then
    result=pass
else
    result=fail
    detail="No result found"
fi

RESULT_AND_SUMMARY="RESULT $result $TEST_NAME $detail"

write_out_result $REPORT \
                 "$TEST_NAME" \
                 "$TEST_DESCRIPTION" \
                 "See activate.log for more details" \
                 "$RESULT_AND_SUMMARY"
